<template>
  <div class="home">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 中间内容区域 -->
      <div class="center-content">
        <!-- 轮播图 -->
        <div class="banner">
          <swiper
            :modules="modules"
            :slides-per-view="1"
            :space-between="0"
            :loop="true"
            :autoplay="{ delay: 5000, disableOnInteraction: false }"
            :pagination="{ clickable: true }"
            :grabCursor="true"
            @swiper="onSwiper"
            @slideChange="onSlideChange"
          >
            <swiper-slide v-for="item in bannerList" :key="item.id">
              <router-link :to="item.link" class="banner-link">
                <img
                  :src="item.imgUrl"
                  alt=""
                  class="banner-image"
                  @error="handleImageError"
                />
                <div class="banner-title">
                  <h2>{{ item.title }}</h2>
                </div>
              </router-link>
            </swiper-slide>
          </swiper>
        </div>

        <!-- 新闻列表 -->
        <div class="news-list">
          <el-empty
            v-if="!loading && newsList.length === 0"
            description="暂无新闻"
          />
          <el-skeleton v-else-if="loading" :rows="3" animated />
          <template v-else>
            <div class="news-header">
              <span class="title">推荐内容</span>
              <span class="date">{{ currentDate }}</span>
            </div>
            <div class="news-container">
              <div v-for="item in newsList" :key="item.id" class="news-item">
                <div class="news-info">
                  <!-- 标题区域可点击跳转 -->
                  <router-link :to="'/news/' + item.id">
                    <h3>{{ item.title }}</h3>
                  </router-link>
                  <div class="news-meta">
                    <span class="source">二次元头条</span>
                    <span class="comments">{{ item.comments }}评论</span>
                    <span class="time">{{ item.time }}</span>
                  </div>
                  <!-- 添加点赞和收藏按钮 -->
                  <div class="news-actions">
                    <span class="action like" @click.stop="handleLike(item)">
                      <el-icon v-if="item.liked"><CirclePlusFilled /></el-icon>
                      <el-icon v-else><CirclePlus /></el-icon>
                      <span>{{ item.likes }} 赞</span>
                    </span>
                    <span
                      class="action collect"
                      @click.stop="handleCollect(item)"
                    >
                      <el-icon v-if="item.collected"><StarFilled /></el-icon>
                      <el-icon v-else><Star /></el-icon>
                      <span>{{ item.collected ? "已收藏" : "收藏" }}</span>
                    </span>
                  </div>
                </div>
                <div class="news-image"></div>
                <!-- 图片区域可点击跳转 -->
                <router-link :to="'/news/' + item.id" class="news-image">
                  <img :src="item.imgUrl" alt="" @error="handleImageError" />
                </router-link>
              </div>
            </div>

            <!-- 加载更多 -->
            <div ref="observerTarget" class="load-more">
              <el-skeleton v-if="loadingMore" :rows="1" animated />
              <span v-else-if="!hasMore" class="no-more">没有更多新闻了</span>
            </div>
          </template>
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="right-content">
        <!-- 搜索框 -->
        <div class="search-box">
          <div class="search-container">
            <el-input
              v-model="searchQuery"
              placeholder="请输入要搜索的关键词"
              @keyup.enter="handleSearch"
              size="large"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
        </div>

        <!-- 24小时头条新闻 -->
        <div class="side-news">
          <div class="section-header" id="hot-head">
            <img
              :src="'/images/backgroundImages/311547.png'"
              alt="新闻图标"
              class="news-icon"
            />
            <h3>热度最高新闻</h3>
          </div>

          <div class="side-news-list">
            <router-link
              v-for="item in sideNewsList"
              :key="item.id"
              :to="'/news/' + item.id"
              class="side-news-item"
            >
              <span class="index" :class="{ hot: item.index <= 3 }">{{
                item.index
              }}</span>
              <div class="news-content">
                <p>{{ item.title }}</p>
                <!-- <span class="like-count">
                  <el-icon><Star /></el-icon>
                  {{ item.likeCount }} 赞
                </span> -->
              </div>
            </router-link>
          </div>
        </div>

        <!-- 在线学习课程 -->
        <div class="side-courses">
          <div class="section-header">
            <h3>广告</h3>
            <a href="https://www.nintendo.com/hk/" class="more" target="_blank"
              >更多</a
            >
          </div>
          <a
            href="https://www.nintendo.com/hk/"
            target="_blank"
            class="course-preview"
          >
            <img :src="banner4" alt="购买Switch2" @error="handleImageError" />
            <div class="course-info">
              <div class="course-title">点击购买Switch2</div>
              <div class="course-tag">任天堂</div>
            </div>
          </a>
          <a
            href="https://www.nintendo.com/hk/"
            target="_blank"
            class="view-more"
            >立即购买</a
          >
        </div>

        <!-- 热门话题 -->
        <!-- <div class="hot-topics">
          <div class="section-header">
            <h3>热门话题</h3>
            <a href="#" class="more">更多</a>
          </div>
          <div class="topic-list">
            <div class="topic-item" v-for="topic in hotTopics" :key="topic.id">
              <div class="topic-title">{{ topic.title }}</div>
              <div class="topic-meta">
                <span class="read-count">{{ topic.readCount }}阅读</span>
                <span class="discuss-count">{{ topic.discussCount }}讨论</span>
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </div>

    <!-- 登录弹框 -->
    <LoginDialog ref="loginDialogRef" />

    <!-- <FlyingAd /> -->
  </div>
</template>

<script setup>
import FlyingAd from "@/components/FlyingAd.vue";
import LoginDialog from "@/components/LoginDialog.vue";
import { ref, computed, onMounted, reactive, watch, onUnmounted } from "vue";
import { Search, ArrowUp, StarFilled, Star } from "@element-plus/icons-vue";
import axios from "axios";
import { useUserStore } from "@/store/user";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Swiper, SwiperSlide } from "swiper/vue";
import { Autoplay, Pagination, Navigation, Mousewheel } from "swiper/modules";
import banner4 from "@/assets/images/banner4.jpg";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const modules = [Autoplay, Pagination, Navigation, Mousewheel];

// 当前日期
const currentDate = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  return `${year}.${month}.${day} ${weekdays[now.getDay()]}`;
});

const loading = ref(false);
const currentPage = ref(1);
const hasMore = ref(true);
const loadingMore = ref(false);
const observerTarget = ref(null);
const searchQuery = ref("");

// 轮播图数据
const bannerList = ref([]);

// 接收新闻列表数据
const newsList = ref([]);

// 右侧新闻数据
const sideNewsList = ref([]);

// 获取热门新闻数据（点赞量最高的前5条）
const fetchHotNews = async () => {
  try {
    const response = await axios.get("/app/news/hotNews?limit=5");
    if (response.data.code === 200) {
      sideNewsList.value = response.data.data.map((news, index) => ({
        id: news.id,
        title: news.title,
        likeCount: news.likeCount || 0,
        index: index + 1,
      }));
    }
  } catch (error) {
    console.error("获取热门新闻失败:", error);
    // 保持原有的静态数据作为后备
    sideNewsList.value = [
      {
        id: 1,
        title: '天津津南一居民楼惊现国二保红隼隼,引发"猫头鹰&鸽子"大猜想',
        likeCount: 0,
        index: 1,
      },
      {
        id: 2,
        title: "武汉大学退休教授愿意资助高考完挑行李回家的女生",
        likeCount: 0,
        index: 2,
      },
      {
        id: 3,
        title: '教育部拟同意设置10所"新大学"!今天(11日),教育部官网发布消息',
        likeCount: 0,
        index: 3,
      },
      {
        id: 4,
        title: "杭州男子失恋游湖南,遇苗族婚宴随礼1000入席,离场却被伴娘拦下",
        likeCount: 0,
        index: 4,
      },
      {
        id: 5,
        title: "周彪接受纪律审查和监察调查",
        likeCount: 0,
        index: 5,
      },
    ];
  }
};

// 热门话题数据
const hotTopics = ref([
  {
    id: 1,
    title: "#化学实验安全规范",
    readCount: "156万",
    discussCount: "2.3万",
  },
  {
    id: 2,
    title: "#乒超联赛精彩瞬间",
    readCount: "132万",
    discussCount: "1.8万",
  },
  { id: 3, title: "#教育政策新变化", readCount: "98万", discussCount: "1.2万" },
  {
    id: 4,
    title: "#校园安全防护指南",
    readCount: "87万",
    discussCount: "8560",
  },
]);

// 登录相关的响应式数据
const loginDialogRef = ref();

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = banner1;
};

// 处理分类变化
const handleCategoryChange = (categoryId) => {
  console.log("Category change event received:", categoryId);
  fetchNewsByCategory(categoryId);
};

// 处理搜索
const handleSearch = () => {
  if (!searchQuery.value.trim()) return;

  // 新增路由跳转
  router.push({
    path: "/search",
    query: { q: searchQuery.value.trim() },
  });
};

// 获取轮播图中的新闻
const fetchRelatedNews = async () => {
  try {
    const response = await axios.get("/app/news/related");
    if (response.data.code === 200) {
      // 转换数据格式为轮播图所需结构
      bannerList.value = response.data.data.map((news) => ({
        id: news.id,
        title: news.title,
        imgUrl: news.picPath,
        link: `/news/${news.id}`,
      }));
    }
  } catch (error) {
    console.error("获取相关新闻失败:", error);
    // 使用后备图片
    bannerList.value = [
      {
        id: 1,
        title: "相关新闻加载失败",
        imgUrl: "/images/default-banner.jpg",
        link: "#",
      },
    ];
  }
};

// 获取新闻数据
const fetchNewsByCategory = async (categoryId, isLoadMore = false) => {
  if (!isLoadMore) {
    loading.value = true;
  } else {
    loadingMore.value = true;
  }
  try {
    // 1. 获取新闻列表
    const newsResponse = await axios.get(
      `/app/news/searchNews?keyword=&categoryId=${categoryId}&pageNo=${currentPage.value}&pageSize=10`
    );
    const newsData = newsResponse.data.data.list;

    // 检查是否还有更多数据
    hasMore.value = newsData.length === 10;

    // 2. 获取所有新闻的评论总数
    const commentCountResponse = await axios.get("/app/comments/commentCount");
    const commentCountData = commentCountResponse.data.data;

    // 3. 创建评论总数映射表 (contentId -> commentCount)
    const commentCountMap = {};
    commentCountData.forEach((item) => {
      commentCountMap[item.contentId] = item.commentCount;
    });

    // 获取所有新闻点赞数
    const likesResponse = await axios.get("/app/like/allCount");
    const likesData = likesResponse.data.data;

    // 创建点赞数映射表 (contentId -> likeCount)
    const likesMap = {};
    likesData.forEach((item) => {
      likesMap[item.contentId] = item.likeCount;
    });

    // 获取当前用户点赞状态
    const userLikesMap = {};
    if (userStore.token) {
      const userLikesResponse = await axios.get(
        `/app/like/userLikes?userId=${userStore.userInfo.id}`
      );
      userLikesResponse.data.data.forEach((item) => {
        userLikesMap[item] = true;
      });
    }

    // 获取用户收藏状态
    let favoritesMap = {};
    if (userStore.token) {
      try {
        const favResponse = await axios.get(
          `/app/favorites/list?userId=${userStore.userInfo.id}`
        );
        if (favResponse.data.code === 200) {
          favResponse.data.data.forEach((item) => {
            favoritesMap[item.contentId] = true;
          });
        }
      } catch (error) {
        console.error("获取收藏列表失败:", error);
      }
    }

    // 构建新闻列表并添加点赞数和收藏状态
    const formattedNews = newsData.map((news) => ({
      id: news.id,
      title: news.title,
      imgUrl: news.picPath,
      source: news.source || "课头条",
      time: formatTime(news.createDate),
      comments: commentCountMap[news.id] || 0,
      likes: likesMap[news.id] || 0,
      liked: !!userLikesMap[news.id],
      collected: !!favoritesMap[news.id],
    }));

    // 如果是加载更多，则追加到现有列表
    if (isLoadMore) {
      newsList.value = [...newsList.value, ...formattedNews];
    } else {
      newsList.value = formattedNews;
    }
  } catch (error) {
    console.error("获取新闻列表失败:", error);
  } finally {
    if (!isLoadMore) {
      loading.value = false;
    } else {
      loadingMore.value = false;
    }
  }
};

// 格式化时间
const formatTime = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now - date;

  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 新增：点赞操作队列
const likeOperations = ref([]);

// 修改后的点赞处理函数
const handleLike = (item) => {
  if (!parseInt(userStore.userInfo?.id)) {
    loginDialogRef.value.show();
    ElMessage.warning("请先登录");
    return;
  }

  const userId = userStore.userInfo.id;
  const wasLiked = item.liked;

  // 更新UI状态
  item.liked = !wasLiked;
  if (item.liked) {
    item.likes++;
  } else {
    item.likes = Math.max(0, item.likes - 1);
  }

  // 记录操作（不立即发送请求）
  const operation = {
    type: item.liked ? "add" : "cancel",
    userId,
    contentId: item.id,
    timestamp: new Date().getTime(),
  };

  // 添加到操作队列
  likeOperations.value.push(operation);

  // 保存到sessionStorage
  saveOperationsToStorage();
};

// 保存操作到sessionStorage
const saveOperationsToStorage = () => {
  try {
    sessionStorage.setItem(
      "pendingLikeOperations",
      JSON.stringify(likeOperations.value)
    );
  } catch (e) {
    console.error("保存操作失败:", e);
  }
};

// 从sessionStorage加载操作
const loadOperationsFromStorage = () => {
  try {
    const data = sessionStorage.getItem("pendingLikeOperations");
    if (data) {
      likeOperations.value = JSON.parse(data) || [];
    }
  } catch (e) {
    console.error("加载操作失败:", e);
  }
};

// 发送所有待处理的操作
const flushLikeOperations = async () => {
  if (likeOperations.value.length === 0) return;

  try {
    // 创建批量操作请求
    const operations = likeOperations.value.map((op) => ({
      type: op.type,
      userId: op.userId,
      contentId: op.contentId,
    }));

    const response = await axios.post("/app/like/batch", {
      operations,
    });

    if (response.data.code === 200) {
      // 清空操作队列
      likeOperations.value = [];
      sessionStorage.removeItem("pendingLikeOperations");
    } else {
      console.error("批量操作失败:", response.data.msg);
    }
  } catch (error) {
    console.error("批量操作请求失败:", error);
  }
};

// 页面事件监听
const handlePageUnload = () => {
  if (likeOperations.value.length > 0) {
    // 使用sendBeacon确保在页面关闭时可靠发送
    const data = JSON.stringify({
      operations: likeOperations.value,
    });

    navigator.sendBeacon("/app/like/batch", data);
  }
};

// 处理收藏
const handleCollect = async (item) => {
  if (!userStore.token) {
    loginDialogRef.value.show();
    ElMessage.warning("请先登录");
    return;
  }

  const userId = userStore.userInfo.id;
  const newsId = item.id;
  const isCollected = item.collected;

  try {
    // 调用收藏API
    const url = isCollected
      ? `/app/favorites/cancel/${userId}/${newsId}`
      : `/app/favorites/add/${userId}/${newsId}`;

    const response = await axios.post(url);

    if (response.data.code === 200) {
      // 更新本地状态
      item.collected = !isCollected;
      ElMessage.success(item.collected ? "收藏成功" : "已取消收藏");
    } else {
      ElMessage.error(response.data.msg || "操作失败");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

// 监听登录对话框事件
onMounted(() => {
  window.addEventListener("show-login-dialog", loginDialogRef.value.show);
  // 首先尝试从sessionStorage恢复用户状态
  const token = sessionStorage.getItem("token");
  const userInfoStr = sessionStorage.getItem("userInfo");

  // 加载未完成的操作
  loadOperationsFromStorage();

  // 添加页面卸载监听
  window.addEventListener("beforeunload", handlePageUnload);

  // 修复后的页面刷新检测
  let isPageRefreshed = false;

  // 方法1: 使用现代API
  const navigationEntries = performance.getEntriesByType("navigation");
  if (navigationEntries.length > 0) {
    isPageRefreshed = navigationEntries[0].type === "reload";
  }
  // 方法2: 兼容性回退方案
  else if (performance.navigation) {
    // 仅在不支持新API的旧浏览器中使用
    isPageRefreshed = performance.navigation.type === 1;
  }

  if (isPageRefreshed) {
    flushLikeOperations(); // 刷新后提交待处理操作
  }

  console.log("尝试从sessionStorage恢复:", {
    token,
    userInfoStr,
  });

  if (token && userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr);
      userStore.setToken(token);
      userStore.setUserInfo(userInfo);
      console.log("成功从session恢复用户状态:", userInfo);
    } catch (error) {
      console.error("恢复用户状态失败:", error);
      // 清除可能损坏的数据
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
    }
  }

  // 然后检查URL中是否有登录数据
  const loginData = route.query.loginData;
  if (loginData) {
    try {
      console.log("检测到登录数据:", loginData);
      const data = JSON.parse(decodeURIComponent(loginData));
      console.log("解析后的登录数据:", data);

      // 更新用户状态
      userStore.setToken(data.token);
      const userInfo = {
        username: data.userName,
        userType: data.userType,
        id: data.id,
        avatar: data.avatar || "",
      };
      userStore.setUserInfo(userInfo);

      // 将用户数据存储到sessionStorage
      try {
        sessionStorage.setItem("token", data.token);
        sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
        console.log("已存储URL登录数据到session:", {
          token: data.token,
          userInfo,
        });
      } catch (storageError) {
        console.error("存储URL登录数据到session失败:", storageError);
      }

      // 清除URL中的参数
      router.replace({ query: {} });
    } catch (error) {
      console.error("解析登录数据失败:", error);
      ElMessage.error("登录数据解析失败，请重新登录");
    }
  }

  // 获取初始新闻数据
  fetchNewsByCategory(route.query.category || 1);

  // 获取热门新闻数据
  fetchHotNews();

  setupInfiniteScroll();

  fetchRelatedNews();
});

// 监听路由参数变化
watch(
  () => route.query.category,
  (newCategory) => {
    console.log("Route category changed:", newCategory);
    currentPage.value = 1; // 重置页码
    hasMore.value = true; // 重置加载状态
    if (newCategory) {
      fetchNewsByCategory(Number(newCategory));
    } else {
      fetchNewsByCategory(1);
    }
  },
  { immediate: true }
);

// 设置无限滚动
const setupInfiniteScroll = () => {
  const observer = new IntersectionObserver(
    async (entries) => {
      const target = entries[0];
      if (target.isIntersecting && !loadingMore.value && hasMore.value) {
        currentPage.value++;
        await fetchNewsByCategory(route.query.category || 1, true);
      }
    },
    {
      threshold: 0.1,
    }
  );

  // 监听目标元素
  if (observerTarget.value) {
    observer.observe(observerTarget.value);
  }

  // 组件卸载时清理
  onUnmounted(() => {
    observer.disconnect();
    window.removeEventListener("beforeunload", handlePageUnload);
  });
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

h3 {
  color: inherit; /* 让标题颜色继承父元素的颜色 */
}
.home {
  min-height: 100vh;
  /* 添加背景图片 */
  background-image: url("/images/backgroundImages/blueArchive3.jpg"); /* 图片路径 */
  background-size: cover; /* 覆盖整个区域 */
  background-position: center; /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; /* 固定背景 */
}

/* 修改主要内容区域为半透明 */
.center-content {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.85); /* 85%不透明度 */
  border-radius: 4px;
  overflow: hidden;
  margin-right: 20px;
}

/* 右侧区域区块也改为半透明 */
.search-container,
.side-news,
.side-courses,
.hot-topics {
  background-color: rgba(255, 255, 255, 0.85) !important; /* 85%不透明度 */
}

/* 主要内容区域样式 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  padding: 0 15px;
}

.banner {
  width: 100%;
  height: 400px; /* 设置合适的高度 */
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.swiper {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  width: 100%;
  height: 100%;
  position: relative;
}

.banner-link {
  display: block;
  width: 100%;
  height: 100%;
  position: relative;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.5s ease;
}

.banner-link:hover .banner-image {
  transform: scale(1.03);
}

.banner a {
  display: block;
  width: 100%;
  height: 100%;
  position: relative;
}

:deep(.el-carousel__item) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner img {
  width: 100%;
  height: 100%;
}

.banner-title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px 40px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  color: white;
  z-index: 10;
}

.banner-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  max-width: 80%;
  line-height: 1.4;
}
:deep(.swiper-pagination-bullet) {
  width: 10px;
  height: 10px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 1;
}

:deep(.swiper-pagination-bullet-active) {
  background: #fff;
}

/* 新闻列表样式 */
.news-list {
  padding: 20px 30px 30px;
}

.news-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 15px;
}

.news-header .title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
}

.news-header .date {
  font-size: 14px;
  color: #999;
}

.news-container {
  display: flex;
  flex-direction: column;
}

.news-item {
  display: flex;
  justify-content: space-between;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.news-item:hover {
  background-color: #fafafa;
}

.news-info h3 {
  color: #333;
  text-decoration: none;
}

.news-item:hover h3 {
  color: #f85959;
}

.news-info {
  flex: 1;
  padding-right: 20px;
}

.news-info h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 500;
  line-height: 1.5;
  transition: color 0.2s;
}

.news-meta {
  display: flex;
  font-size: 14px;
  color: #999;
}

.news-meta span {
  margin-right: 20px;
}

.news-meta .source {
  color: #64cbff;
}

.news-meta .comments {
  color: #5079d9;
}

.news-image {
  width: 180px;
  height: 120px;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

/* 新增的新闻操作按钮样式 */
.news-actions {
  display: flex;
  margin-top: 10px;
  gap: 15px;
}

.action {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.action:hover {
  color: #f85959;
}

.action .el-icon {
  margin-right: 5px;
  font-size: 16px;
}

.action.collect.active {
  color: #ffc300;
}

/* 右侧区域样式 */
.right-content {
  width: 300px;
}

.search-box {
  margin-bottom: 20px;
}

/* .search-container {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
} */

/* 侧边栏区块公共样式 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #222;
}

.section-header .more {
  font-size: 14px;
  color: #999;
  text-decoration: none;
}

.section-header .more:hover {
  color: #f85959;
}

/* 24小时头条样式 */
.side-news {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.side-news-list {
  display: flex;
  flex-direction: column;
}

.side-news-item {
  display: flex;
  padding: 12px 0;
  text-decoration: none;
  color: #222;
  border-bottom: 1px solid #f5f5f5;
}

.side-news-item:last-child {
  border-bottom: none;
}

.side-news-item:hover p {
  color: #f85959;
}

.side-news-item .index {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  font-size: 14px;
  color: #999;
  margin-right: 12px;
}

.side-news-item .index.hot {
  background-color: #64cbff;
  color: white;
  border-radius: 50%;
}

.side-news-item .news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.side-news-item p {
  margin: 0;
  font-size: 15px;
  line-height: 1.5;
  transition: color 0.2s;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.side-news-item .like-count {
  font-size: 12px;
  color: #f85959;
  display: flex;
  align-items: center;
  gap: 4px;
}

.side-news-item .like-count .el-icon {
  font-size: 14px;
}

/* 在线课程样式 */
.side-courses {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.course-preview {
  position: relative;
  margin-bottom: 15px;
  display: block;
  text-decoration: none;
  cursor: pointer;
  transition: opacity 0.3s;
}

.course-preview:hover {
  opacity: 0.9;
}

.course-preview img {
  width: 100%;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
}

.course-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.course-title {
  font-size: 15px;
  font-weight: 500;
}

.course-tag {
  background-color: #ffc300;
  color: #222;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 3px;
}

.view-more {
  width: 100%;
  padding: 10px 0;
  background-color: #fff;
  color: #f85959;
  border: 1px solid #f85959;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s;
  display: block;
  text-decoration: none;
}

.view-more:hover {
  background-color: #fffaf0;
  border-color: #ff7e7e;
}

/* 热门话题样式 */
/* 添加图片样式 */
.news-icon {
  width: 50px;
  height: 50px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 4px;
}
#hot-head {
  justify-content: start;
}

.hot-topics {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.topic-list {
  display: flex;
  flex-direction: column;
}

.topic-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.topic-item:last-child {
  border-bottom: none;
}

.topic-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #222;
}

.topic-meta {
  display: flex;
  font-size: 13px;
  color: #999;
}

.topic-meta span {
  margin-right: 15px;
}

/* 登录弹框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 30px 20px 20px;
  text-align: center;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 10px 40px 30px;
}

.login-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

:deep(.el-input__wrapper) {
  padding: 1px 15px;
}

:deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
}

.agreement-text {
  text-align: center;
  color: #666;
  font-size: 14px;
}

.agreement-text a {
  color: #1890ff;
  text-decoration: none;
}

.agreement-text a:hover {
  color: #40a9ff;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  background-color: #f85959;
  border-color: #f85959;
}

.login-button:hover {
  background-color: #ff7070;
  border-color: #ff7070;
}

:deep(.el-dialog__footer) {
  display: none;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
}

.username {
  margin-left: 8px;
  font-size: 14px;
  color: #333;
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 20px;
}

.load-more {
  padding: 20px 0;
  text-align: center;
}

.no-more {
  color: #999;
  font-size: 14px;
}
</style>
